package ensemble.controls

import net.oschina.oldpig.snout.{FxContext, NodeFactory}
import javafx.scene.layout.VBox
import javafx.application.Platform
import javafx.event.ActionEvent
import javafx.stage.{Stage, Screen}
import javafx.geometry.Rectangle2D

object WindowButtons extends NodeFactory[VBox] {
  var maximized = false
  var backupWindowBounds: Rectangle2D = null
  var stage: Stage = _

  def createInstance = {
    val result = new VBox
    import net.oschina.oldpig.snout.FxBuilder._
    builderParent.withValue(result) {
      button(id := "window-close", onAction := { _ => Platform.exit()})
      button(id := "window-min", onAction := onMinimize)
      button(id := "window-max", onAction := toggleMaximized)
    }
    result
  }

  /**
   * this method was apply(stg: Stage, attr:(VBox=>Unit)*): VBox but the compiler emit
   * ambiguous implicit error
   * @param stg
   * @param attr
   * @return
   */
  def apply(stg: Stage)(attr: (VBox => Unit)*): VBox = {
    stage = stg
    apply(attr:_*)
  }

  def onMinimize(e: ActionEvent) = {
    stage.setIconified(true)
  }

  def toggleMaximized(e: ActionEvent) = {
    val screen = Screen.getScreensForRectangle(stage.getX, stage.getY, 1, 1).get(0)
    if (maximized) {
      maximized = false
      if (backupWindowBounds != null) {
        stage.setX(backupWindowBounds.getMinX)
        stage.setY(backupWindowBounds.getMinY)
        stage.setWidth(backupWindowBounds.getWidth)
        stage.setHeight(backupWindowBounds.getHeight)
      }
    } else {
      maximized = true
      backupWindowBounds = new Rectangle2D(stage.getX, stage.getY, stage.getWidth, stage.getHeight)
      stage.setX(screen.getVisualBounds.getMinX)
      stage.setY(screen.getVisualBounds.getMinY)
      stage.setWidth(screen.getVisualBounds.getWidth)
      stage.setHeight(screen.getVisualBounds.getHeight)
    }
  }
}
